import Grid2Canvas from "./mapConfig/gird";
import { pointInfo } from "./mapConfig/config/mapConfig";
import sjccKey from "@/config/sjmapkey";
import resourceJson from "../../EmergencyResources/components/map";
import colorLines from "./mapConfig/config/colorLines";
import { getByAreaNameAndTime, getGridByAreaAndTime, getEarlyWarningList } from "@/api/common";
import { listPage } from "@/api/EarlyWarningManagement/yjtzd";
import { xymldSubmissionList } from "@/api/EmergencyDisposal/xymld";
import { hbcitys } from "./hbcitys";
import moment from "moment";
export default {
  data() {
    return {
      tucengvalues: [true, false, false, false, false, false, false, false],
      mapType: "sb",
      tenData: [
        { areaName: "武汉", daytimeWeather: "晴" },
        { areaName: "荆州", daytimeWeather: "晴" },
        { areaName: "十堰市", daytimeWeather: "晴" },
        { areaName: "襄阳市", daytimeWeather: "晴" },
        { areaName: "神农架林区", daytimeWeather: "晴" },
        { areaName: "随州市", daytimeWeather: "晴" },
        { areaName: "潜江市", daytimeWeather: "晴" },
        { areaName: "恩施土家族苗族自治州", daytimeWeather: "晴" },
        { areaName: "宜昌市", daytimeWeather: "晴" },
        { areaName: "仙桃市", daytimeWeather: "晴" },
        { areaName: "黄冈市", daytimeWeather: "晴" },
        { areaName: "咸宁市", daytimeWeather: "晴" },
        { areaName: "荆门市", daytimeWeather: "晴" },
        { areaName: "孝感市", daytimeWeather: "阴" }
      ],
      temperatureCanvas: null,
      qxtyids: [true, false, false],
      qxtypes: [
        {
          name: "气温",
          value: "1"
        },
        {
          name: "降水",
          value: "2"
        },
        {
          name: "风速",
          value: "3"
        },
        {
          name: "气象预警",
          value: "4"
        }
        // {
        //   name: "雷暴",
        //   value: "4"
        // }
      ],
      markersOnScreen: {},
      tqtbObj: {
        暴雪: "baoxue",
        暴雨: "baoyu",
        大雪: "daxue",
        大雨: "dayu",
        大雨转晴: "dayuzhuanqing",
        多云: "duoyun",
        多云转晴: "duoyunzq",
        晴转多云: "duoyunzq",
        雷阵雨: "leizyu",
        晴: "qing",
        闪电: "shandian",
        少云: "shaoyun",
        特大阵雨: "tedazhenyu",
        雾霾: "wumai",
        雾天: "wutian",
        小雪: "xiaoxue",
        小雨: "xiaoyu",
        扬沙: "yangsha",
        阴天: "yintian",
        雨夹雪: "yujiaxue",
        阵雨: "zhenyu",
        阵雨转晴: "zhenyuzhuanqing",
        中雪: "zhongxue",
        中雨: "zhongyu",
        中雨转小雨: "zhongyu",
        小雨转中雨: "zhongyu",
        阴转中雨: "zhongyu",
        晴转小雨: "xiaoyu",
        多云转小雨: "xiaoyu",
        小雨转阴: "xiaoyu",
        小雨转晴: "xiaoyu",
        阴转小雨: "xiaoyu",
        小雨转多云: "xiaoyu",
        晴转阴: "yintian",
        多云转阴: "yintian",
        阴: "yintian",
        阴转晴: "yintian",
        阴转多云: "yintian"
      }
    };
  },
  methods: {
    async createMaker(params) {
      const arr = await getByAreaNameAndTime("", "");
      if (arr.length > 0) {
        this.tenData = arr.map(el => {
          return { areaName: el.areaname, daytimeWeather: el.dgdWp12 };
        });
      }
      if (!this.tenData.length || !this.weathermap || !this.weathermap.map) return;
      const features = this.weathermap.map.getSource("power-polygen-symbol").serialize().data.features;
      const citys = features.filter(i => i.properties.level === "city");
      for (const feature of citys) {
        const coords = feature.geometry.coordinates;
        const props = feature.properties;
        const id = props.name;
        const adcode = props.adcode;
        let marker = this.markersOnScreen[id];
        if (!marker) {
          const item = this.tenData.find(i => id.startsWith(i.areaName));
          if (!item) continue;
          const el = document.createElement("div");
          const type = this.tqtbObj[item.daytimeWeather] || "qing";
          const img = require(`@/assets/img/tqtb/${type}.png`);
          el.innerHTML = `<img id=${id} class=${adcode} src="${img}" alt="" style="width: 45px;height: 45px;margin-top: -40px;"/>`;
          marker = new SGMap.Marker(el).setLngLat(coords);
          marker.addTo(this.weathermap.map);
          this.$set(this.markersOnScreen, [id], marker);
        } else {
          const item = this.tenData.find(i => id.startsWith(i.areaName));
          if (!item) continue;
          const type = this.tqtbObj[item.daytimeWeather];
          const img = require(`@/assets/img/tqtb/${type}.png`);
          const idStr = `#${id}`;
          document.querySelector(`${idStr}`).setAttribute("src", img);
        }
      }
      // 返回一个清理marker的函数
      const clear = () => {
        for (const id in this.markersOnScreen) {
          if (this.markersOnScreen[id]) {
            this.markersOnScreen[id].remove();
            this.markersOnScreen[id] = null;
          }
        }
      };
      this.clearMarker = clear;
      return clear;
    },
    getGridData(type = "temperature") {
      const obj = {
        wind: "EDA10",
        temperature: "TMP",
        rain: "ER03"
      };
      getGridByAreaAndTime(obj[type]).then(res => {
        if (res && res.length > 0) {
          const data = {
            fileName:
              "Z_NWGD_C_BCWH_10211009100757_P_RFFC_SPCC-TMP_102110090800_14003.GRB2",
            gridInfo: {
              lonNum: 311,
              lonMax: 116.15,
              lonSpan: 0.01505684,
              latSpan: 0.0150113,
              latMin: 18.9,
              lonMin: 108.15,
              latMax: 33.4,
              latNum: 181
            },
            gridData: JSON.parse(res[0].griddata)
          };
          if (type === "temperature") this.setProperty(data);
          if (this.temperatureCanvas) {
            this.temperatureCanvas.update(data, colorLines[type]);
          } else {
            this.temperatureCanvas = this.createLayerByGrayImage({
              canvasContainer: document.querySelector("#temperature"),
              data,
              colorConfig: colorLines[type],
              map: this.map
            });
          }
        } else {
          this.getRandomGrid(type);
        }
      });
    },
    getRandomGrid(type) {
      const gridData = [];
      for (let i = 0; i < 181; i++) {
        const arr = [];
        for (let j = 0; j < 321; j++) {
          arr.push(Math.floor(Math.random() * 20));
        }
        gridData.push(arr);
      }
      const data = {
        fileName:
          "Z_NWGD_C_BCWH_10211009100757_P_RFFC_SPCC-TMP_102110090800_14003.GRB2",
        gridInfo: {
          lonNum: 311,
          lonMax: 116.15,
          lonSpan: 0.01505684,
          latSpan: 0.0150113,
          latMin: 18.9,
          lonMin: 108.15,
          latMax: 33.4,
          latNum: 181
        }
      };
      data.gridData = gridData;
      if (type === "temperature") this.setProperty(data);
      if (this.temperatureCanvas) {
        this.temperatureCanvas.update(data, colorLines[type]);
      } else {
        this.temperatureCanvas = this.createLayerByGrayImage({
          canvasContainer: document.querySelector("#temperature"),
          data,
          colorConfig: colorLines[type],
          map: this.map
        });
      }
    },
    windScene() {
      this.getGridData("wind");
    },
    qxyjScene() {
      if (this.temperatureCanvas) {
        this.temperatureCanvas.remove();
        this.temperatureCanvas = null;
      }
      this.clearMarker();
      const starttime = moment().subtract(1, "days").format("YYYY-MM-DD HH:mm:ss");
      const endtime = moment().format("YYYY-MM-DD HH:mm:ss");
      const params = {
        pageNum: 1,
        pageSize: 50,
        starttime,
        endtime
      };
      getEarlyWarningList(params).then(res => {
        const levels = {
          "红色": "hongse",
          "橙色": "chengse",
          "蓝色": "lanse",
          "黄色": "huangse"
        };
        const types = {
          "暴雪": "baoxue",
          "暴雨": "baoyu",
          "冰雹": "bingbao",
          "大风": "dafeng",
          "道路结冰": "daolujiebing",
          "大雾": "dawu",
          "干旱": "ganhan",
          "高温": "gaowen",
          "寒潮": "hanchao",
          "洪涝": "honglao",
          "雷电": "leidian",
          "霾": "mai",
          "霜冻": "shuangdong"
        };
        const arr = res.map(el => {
          return {
            effectRange: el.publishunit.slice(0, -3),
            content: el.content,
            effectarea: el.effectarea,
            publishunit: el.publishunit,
            imgurl: `${types[el.warnsignaltype]}_${levels[el.warnsignallevel]}`
          };
        });
        this.popupYjDOM = new SGMap.Popup({
          closeButton: false,
          closeOnClick: false,
          offset: {
            bottom: [0, 0]
          }
        });
        const newArr = [];
        const cityArr = [];
        arr.forEach(el => {
          if (!cityArr.includes(el.effectRange)) {
            cityArr.push(el.effectRange);
            if (!el.imgurl.includes("undefined")) {
              const item = hbcitys.find(city => city.name === el.effectRange);
              if (item) {
                el.center = item.center;
                newArr.push(el);
              }
            }
          }
        });
        if (newArr.length === 0) return;
        this.drawQxYj(newArr);
      });
    },
    drawQxYj(newArr) {
      const features = [];
      const imgurls = [];
      newArr.forEach(el => {
        const center = el.center.split(",");
        const jd = Number(center[0]);
        const wd = Number(center[1]);
        if (!imgurls.includes(el.imgurl)) imgurls.push(el.imgurl);
        features.push(
          {
            type: "Feature",
            geometry: {
              type: "Point",
              coordinates: [jd, wd]
            },
            properties: {
              effectRange: el.effectRange,
              imgurl: el.imgurl,
              content: el.content,
              effectarea: el.effectarea,
              publishunit: el.publishunit
            }
          }
        );
      });
      this.popupYjDOM = new SGMap.Popup({
        closeButton: false,
        closeOnClick: false,
        offset: {
          bottom: [0, 0]
        }
      });
      imgurls.forEach(el => {
        if (!this.map.hasImage(el)) {
          var url = require(`@/assets/map/weather/${el}.png`);
          this.map.loadImage(url, (error, image) => {
            this.map.addImage(el, image);
          });
        }
      });
      this.map.addLayer({
        id: "yjImgLayer",
        type: "symbol",
        source: {
          type: "geojson",
          data: {
            type: "FeatureCollection",
            features
          }
        },
        layout: {
          "icon-image": "{imgurl}",
          "icon-size": 0.2,
          "icon-ignore-placement": true,
          "text-ignore-placement": false,
          "text-size": 12,
          "text-anchor": "top",
          "text-allow-overlap": false,
          "icon-anchor": "center",
          "text-offset": [0, 0],
          "text-max-width": 8,
          "text-font": ["Microsoft YaHei Regular"]
        }
      });
      var bkurl = require("../../../assets/map/tancfc.png");
      this.map.on("mouseenter", "yjImgLayer", (e) => {
        var properties = e.features[0].properties;
        const h = Math.ceil(properties.content.length / 24) * 20;
        this.popupYjDOM.setLngLat([e.lngLat.lng, e.lngLat.lat]).setHTML(
          `<div style="width:620px;height:240px;display:flex;flex-direction:column;background: url(${bkurl});background-size: 100% 100%;padding:20px;">
            <div style="font-size:24px;color:#fff;padding:6px;height: 32px;line-height: 32px;margin-bottom: ${h}px;">${properties.content}</div>
            <div style="font-size:24px;color:#fff;padding:6px;height: 32px;line-height: 32px;margin-bottom: 6px;">影响区域：${properties.effectarea}</div>
            <div style="font-size:24px;color:#fff;padding:6px;height: 32px;line-height: 32px;margin-bottom: 6px;">发布单位：${properties.publishunit}</div>

          </div>`
        ).addTo(this.map);
      });
      this.map.on("mouseleave", "yjImgLayer", (e) => {
        this.popupYjDOM.remove();
      });
    },
    rainScene() {
      this.getGridData("rain");
    },
    handleqxtypeChange(key) {
      this.clearYjImg();
      this.qxtyids.forEach((el, index) => {
        if (index !== key) {
          this.qxtyids[index] = false;
        }
      });
      const qxArr = ["temperature", "rain", "wind", "qxyj"];
      this.weatherType = qxArr[key];
      this[`${this.weatherType}Scene`]();
    },
    // 修改标注下面的数值，温度，降水量等等
    setProperty(data, unit = "℃") {
      const source = this.weathermap.map.getSource("power-polygen-symbol");
      const features = source.serialize().data.features;
      features.forEach(item => {
        const cityname = pointInfo.find(i => item.properties.name.includes(i.areaName)) || { thwartwiseLattice: 1, endlongLattice: 1 };
        if (cityname && data && data.gridData && data.gridData.length > 0) {
          this.weathermap.updateMaker("id" + item.properties.adcode, data.gridData[cityname.endlongLattice - 1][cityname.thwartwiseLattice - 1].toFixed(1) + unit);
        } else {
          this.weathermap.updateMaker("id" + item.properties.adcode, "");
        }
      });
    },
    createLayerByGrayImage({ map, canvasContainer, colorConfig, data }) {
      const canvasLayer = new Grid2Canvas({
        map,
        data,
        colorConfig,
        canvasContainer
      });
      if (!map.getSource("cloud")) {
        map.addSource("cloud", {
          type: "canvas",
          canvas: "temperature",
          coordinates: [
            [108.25, 33.4],
            [116.25, 33.4],
            [116.25, 28.9],
            [108.25, 28.9]
          ]
        });
        map.addLayer({
          before: "power-line",
          id: "cloud-layer",
          "type": "raster",
          "source": "cloud",
          "paint": {
            "raster-fade-duration": 0,
            "raster-opacity": 1
          }
        });
        map.moveLayer("cloud-layer", "power-line");
      } else {
        map.addSource("canvas-source", {
          type: "canvas",
          canvas: "temperature",
          coordinates: [
            [108.25, 33.4],
            [116.25, 33.4],
            [116.25, 28.9],
            [108.25, 28.9]
          ],
          animate: true
        });
      }
      return {
        update: (data, colors) => {
          canvasLayer.setData(data, colors);
        },
        remove: () => {
          map.removeLayer("cloud-layer");
          map.removeSource("cloud");
        }
      };
    },
    clearMarker() {
      for (const id in this.markersOnScreen) {
        if (this.markersOnScreen[id]) {
          this.markersOnScreen[id].remove();
          this.markersOnScreen[id] = null;
        }
      }
    },
    initSourceMaps() {
      const that = this;
      SGMap.tokenTask.login(sjccKey.appkey, sjccKey.appsecret).then((res) => {
        this.map = new SGMap.Map({
          container: "warrmapcomponents",
          style: "aegis://styles/aegis/Streets",
          zoom: this.mapZoom,
          center: this.mapCenter,
          localIdeographFontFamily: "Microsoft YoHei"
        });
        this.map.on("load", (e) => {
          // 添加一个geojson类型的数据源，并把cluster属性设置为true，sdk会主动添加point_count、point_count_abbreviated属性到这份数据中
          // point_count是当前聚合点个数，point_count_abbreviated聚合点个数的简写
          // 初始化Popup
          // this.draeHbLine();
          // this.createMaskBorder();
          that.popupDOM = new SGMap.Popup({
            // 是否显示关闭按钮
            closeButton: false,
            closeOnClick: false,
            offset: {
              bottom: [0, 0]
            }
          });
          that.map.addSource("themeData", {
            type: "geojson",
            data: resourceJson,
            cluster: true,
            clusterMaxZoom: 12, // 最大聚类层级
            clusterRadius: 100 // 聚合点半径，默认50
          });
          that.map.addLayer({
            id: "clusters",
            type: "circle",
            source: "themeData",
            filter: ["has", "point_count"],
            paint: {
              // 使用step表达式，用于分段匹配圆点的颜色和半径
              // 根据当前"point_count"值匹配对应的内容
              // 默认为"#9faebf"
              // 当大于10小于30时，返回"#3583de"
              // 大于30小于55时，返回"#04b71e"
              "circle-color": [
                "step",
                ["get", "point_count"],
                "#9faebf",
                2,
                "#3583de",
                4,
                "#04b71e",
                6,
                "#ff9800",
                8,
                "#f61402",
                10,
                "#f61402"
              ],
              "circle-radius": [
                "step",
                ["get", "point_count"],
                20,
                50,
                30,
                100,
                35,
                500,
                35,
                2000,
                40,
                5000,
                40
              ],
              "circle-opacity": 0.7,
              "circle-stroke-width": 3,
              "circle-stroke-color": "#ffffff"
            }
          });

          that.map.addLayer({
            id: "clusterCount",
            type: "symbol",
            source: "themeData",
            filter: ["has", "point_count"],
            layout: {
              "text-field": "{point_count_abbreviated}",
              "text-font": ["Microsoft YaHei Regular"],
              "text-size": 14
            },
            paint: {
              "text-color": "#ffffff"
            }
          });

          // 监听聚类图点击，并且根据点击的聚合圆展开
          that.map.on("click", "clusters", (e) => {
            var features = that.map.queryRenderedFeatures(e.point, {
              layers: ["clusters"]
            });
            var clusterId = features[0].properties.cluster_id;

            that.map
              .getSource("themeData")
              .getClusterExpansionZoom(clusterId, (err, zoom) => {
                if (err) return;
                that.map.easeTo({
                  center: features[0].geometry.coordinates,
                  zoom: zoom
                });
              });
          });

          // 画图片点，需要先加载图片 图片路径在页面部署在服务上时可以用相对路径
          var url = require("../../../assets/img/fangzi.png");
          that.map.loadImage(url, (error, image) => {
            // 添加图片到map，可以设置图片id
            that.map.addImage("poi", image);
            that.map.addLayer({
              id: "choicePoi",
              type: "symbol",
              source: "themeData",
              filter: ["!has", "point_count"],
              layout: {
                "icon-image": "poi",
                "icon-size": 0.2
              },
              paint: {
                "text-color": "#555252",
                "text-halo-color": "#FFFFFF",
                "text-halo-width": 1.33333
              }
            });
          });
          that.map.on("mouseenter", "choicePoi", (e) => {
            const properties = e.features[0].properties;
            that.popupDOM.setLngLat([e.lngLat.lng, e.lngLat.lat]).setHTML(
              `<div style="display:flex;flex-direction:column;background:#333;">
                <div style="font-size:16px;color:#fff;padding:6px;">${properties.name || "应急物资仓库"}</div>
              </div>`
            ).addTo(that.map);
          });
          that.map.on("mouseleave", "choicePoi", (e) => {
            that.popupDOM.remove();
          });
        });
      });
    },
    initYjMaps(key = "yj") {
      SGMap.tokenTask.login(sjccKey.appkey, sjccKey.appsecret).then((res) => {
        this.map = new SGMap.Map({
          container: "warrmapcomponents",
          style: "aegis://styles/aegis/Streets",
          zoom: this.mapZoom,
          center: this.mapCenter,
          localIdeographFontFamily: "Microsoft YoHei"
        });
        this.map.on("load", (e) => {
          this.draeHbLine();
          if (key === "yj") {
            this.getYjtzdList();
          } else if (key === "xy") {
            this.getXymldList();
          }
        });
      });
    },
    clearYjImg() {
      if (this.map.getLayer("yjImgLayer")) this.map.removeLayer("yjImgLayer");
      if (this.map.getSource("yjImgLayer")) this.map.removeSource("yjImgLayer");
    },
    getYjtzdList() {
      const params = {
        pageNum: 1,
        pageSize: 30
      };
      listPage(params).then(res => {
        const arr = [];
        const citys = [];
        res.data.forEach(el => {
          if (el.effectRange !== "湖北省") {
            const city = this.getYjtzdCity(el.effectRange);
            if (!citys.includes(city)) {
              citys.push(city);
              arr.push({
                dangerName: el.dangerName,
                warningNoticeName: el.warningNoticeName,
                warningLvName: el.warningLvName,
                warningLvCode: el.warningLvCode,
                effectRange: city
              });
            }
          }
        });
        this.popupYjDOM = new SGMap.Popup({
          closeButton: false,
          closeOnClick: false,
          offset: {
            bottom: [0, 0]
          }
        });
        SGMap.plugin(["SGMap.DistrictTask"]).then(() => {
          const districtTask = new SGMap.DistrictTask();
          arr.forEach((el, index) => {
            this.drawYjImg(el, index, districtTask);
          });
        });

      });
    },
    drawYjImg(el, index, districtTask) {
      districtTask.searchDistrict({
        keyword: el.effectRange,
        extension: true,
        subdistrict: "1"
      }).then((result) => {
        const center = result.data.districts[0].center;
        const centerArr = center.split(",");
        const longitude = Number(centerArr[0]);
        const latitude = Number(centerArr[1]);
        const imgObj = {
          "1": "blue",
          "2": "yellow",
          "3": "orange",
          "4": "red"
        };
        var url = require(`../../../assets/map/${imgObj[el.warningLvCode]}.png`);
        this.map.loadImage(url, (error, image) => {
          this.map.addImage("yjImg" + index, image);
          this.map.addLayer({
            id: "yjImgLayer" + index,
            type: "symbol",
            source: {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: [
                  {
                    type: "Feature",
                    geometry: {
                      type: "Point",
                      coordinates: [longitude, latitude]
                    },
                    properties: {
                      name: ""
                    }
                  }
                ]
              }
            },
            layout: {
              "icon-image": "yjImg" + index,
              "icon-size": 0.6,
              "icon-ignore-placement": true,
              "text-ignore-placement": false,
              "text-size": 12,
              "text-anchor": "top",
              "text-allow-overlap": false,
              "icon-anchor": "center",
              "text-offset": [0, 0],
              "text-max-width": 8,
              "text-font": ["Microsoft YaHei Regular"]
            },
            paint: {
              "text-color": "#555252",
              "text-halo-color": "#FFFFFF",
              "text-halo-width": 1.33333
            }
          });
        });
        var bkurl = require("../../../assets/map/tancfc.png");
        this.map.on("mouseenter", "yjImgLayer" + index, (e) => {
          this.popupYjDOM.setLngLat([e.lngLat.lng, e.lngLat.lat]).setHTML(
            `<div style="width:600px;height:240px;display:flex;flex-direction:column;background: url(${bkurl});background-size: 100% 100%;padding:20px;">
            <div style="font-size:24px;color:#fff;padding:6px;height: 32px;line-height: 32px;margin-bottom: 36px;">${el.warningNoticeName}</div>
            <div style="font-size:24px;color:#fff;padding:6px;height: 32px;line-height: 32px;margin-bottom: 6px;">事件类型：${el.dangerName}</div>
            <div style="font-size:24px;color:#fff;padding:6px;height: 32px;line-height: 32px;margin-bottom: 6px;">响应级别：${el.warningLvName}</div>
            <div style="font-size:24px;color:#fff;padding:6px;height: 32px;line-height: 32px;margin-bottom: 6px;">影响范围：${el.effectRange}</div>
            
          </div>`
          ).addTo(this.map);
        });
        this.map.on("mouseleave", "yjImgLayer" + index, (e) => {
          this.popupYjDOM.remove();
        });
      });
    },
    drawXyImg(el, index, districtTask) {
      districtTask.searchDistrict({
        keyword: el.effectRange,
        extension: true,
        subdistrict: "1"
      }).then((result) => {
        const center = result.data.districts[0].center;
        const centerArr = center.split(",");
        const longitude = Number(centerArr[0]);
        const latitude = Number(centerArr[1]);
        const imgObj = {
          "1": "hhsd",
          "2": "csd",
          "3": "hsd",
          "4": "lsd"
        };
        var url = require(`../../../assets/map/${imgObj[el.warningLvCode]}.png`);
        this.map.loadImage(url, (error, image) => {
          this.map.addImage("xyImg" + index, image);
          this.map.addLayer({
            id: "xyImgLayer" + index,
            type: "symbol",
            source: {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: [
                  {
                    type: "Feature",
                    geometry: {
                      type: "Point",
                      coordinates: [longitude, latitude]
                    },
                    properties: {
                      name: ""
                    }
                  }
                ]
              }
            },
            layout: {
              "icon-image": "xyImg" + index,
              "icon-size": 0.6,
              "icon-ignore-placement": true,
              "text-ignore-placement": false,
              "text-size": 12,
              "text-anchor": "top",
              "text-allow-overlap": false,
              "icon-anchor": "center",
              "text-offset": [0, 0],
              "text-max-width": 8,
              "text-font": ["Microsoft YaHei Regular"]
            },
            paint: {
              "text-color": "#555252",
              "text-halo-color": "#FFFFFF",
              "text-halo-width": 1.33333
            }
          });
        });
        var bkurl = require("../../../assets/map/tancfc.png");
        this.map.on("mouseenter", "xyImgLayer" + index, (e) => {
          this.popupXyDOM.setLngLat([e.lngLat.lng, e.lngLat.lat]).setHTML(
            `<div style="width:600px;height:240px;display:flex;flex-direction:column;background: url(${bkurl});background-size: 100% 100%;padding:20px;">
            <div style="font-size:24px;color:#fff;padding:6px;height: 32px;line-height: 32px;margin-bottom: 36px;">${el.warningNoticeName}</div>
            <div style="font-size:24px;color:#fff;padding:6px;height: 32px;line-height: 32px;margin-bottom: 6px;">事件类型：${el.dangerName}</div>
            <div style="font-size:24px;color:#fff;padding:6px;height: 32px;line-height: 32px;margin-bottom: 6px;">响应级别：${el.warningLvName}</div>
            <div style="font-size:24px;color:#fff;padding:6px;height: 32px;line-height: 32px;margin-bottom: 6px;">影响范围：${el.effectRange}</div>
            
          </div>`
          ).addTo(this.map);
        });
        this.map.on("mouseleave", "xyImgLayer" + index, (e) => {
          this.popupXyDOM.remove();
        });
      });
    },
    // 添加边界
    createMaskBorder(adcode) {
      this.createMask();
      return this.getFeature(adcode);
    },
    createMask() {
      // 行政区划边界线
      this.map.addLayer({
        id: "power-line",
        type: "line",
        source: {
          type: "geojson",
          data: {
            type: "FeatureCollection",
            features: []
          }
        },
        paint: {
          "line-color": "#f4b271",
          "line-width": 2
        }
      });
      // 面标注
      this.map.addLayer({
        id: "power-polygen-symbol",
        type: "symbol",
        source: {
          type: "geojson",
          data: {
            type: "FeatureCollection",
            features: []
          }
        }
      });
      // 遮罩面
      this.map.addLayer({
        id: "mask-polygon",
        type: "fill",
        source: {
          type: "geojson",
          data: {
            type: "FeatureCollection",
            features: []
          }
        },
        paint: {
          "fill-color": "#061835",
          "fill-outline-color": "#061835"
        }
      });
    },
    getFeature(adcode) {
      return new Promise((reslove, reject) => {
        const baseURL = process.env.NODE_ENV === "test" ? "test" : "hb-ecs";
        fetch(`/${baseURL}/json/hubei.json`)
          .then((r) => r.json())
          .then((result) => {
            var features = [];
            var featuresSymbol = [];
            var featuresPolygon = [];
            // 外层遮罩方形边界
            var outSideShape = [
              [
                [-180, 90],
                [180, 90],
                [180, -90],
                [-180, -90]
              ]
            ];
            // 主要区分直辖市和其他省份
            var district = result.data.districts[0];
            this.map.district = district;

            const flatarr = (pid, data, children = "sub_districts") => {
              return data.reduce((prev, cur) => {
                return cur[children]
                  ? prev.concat({ pid, ...cur }, flatarr(cur.name, cur[children]))
                  : prev.concat({ pid, ...cur });
              }, []);
            };
            const allDistricts = flatarr(district.name, district.sub_districts).map((item) => ({
              type: "Feature",
              geometry: {
                coordinates: item.center.split(",").map(Number),
                type: "Point"
              },
              properties: {
                level: item.name === "神农架林区" ? "city" : item.level,
                adcode: item.adcode,
                pid: item.pid,
                name: item.name,
                temperature: ""
              }
            }));
            for (var o in district.sub_districts) {
              if (district.sub_districts[o].shape == undefined) continue;
              var shape = district.sub_districts[o].shape;
              // 标注
              featuresSymbol.push({
                type: "Feature",
                geometry: {
                  coordinates: district.sub_districts[o].center.split(",").map(Number),
                  type: "Point"
                },
                properties: {
                  name: district.sub_districts[o].name,
                  temperature: ""
                }
              });
              // 边界
              if (shape.type == "MultiPolygon") {
                for (const o in shape.coordinates) {
                  if (shape.coordinates[o] instanceof Array) {
                    features = features.concat(shape.coordinates[o]);
                  }
                }
              } else {
                features.push(shape.coordinates[0]);
              }
            }
            // 面数据和遮罩
            if (district.shape.type == "MultiPolygon") {
              for (const o in district.shape.coordinates) {
                outSideShape = outSideShape.concat(district.shape.coordinates[o]);
                featuresPolygon = featuresPolygon.concat([district.shape.coordinates[o]]);
              }
            } else {
              outSideShape = outSideShape.concat(district.shape.coordinates);
              featuresPolygon = featuresPolygon.concat(district.shape.coordinates);
            }
            // 更新视图
            // 遮罩
            this.map.getSource("mask-polygon").setData({
              type: "FeatureCollection",
              features: [
                {
                  type: "Feature",
                  geometry: {
                    type: "MultiPolygon",
                    coordinates: [outSideShape]
                  }
                }
              ]
            });
            this.map.getSource("power-polygen-symbol").setData({
              type: "FeatureCollection",
              // features: adcode ? districts : allDistricts,
              features: allDistricts
            });
            reslove(result);
          })
          .catch((e) => reject(e));
      });
    },
    getXymldList() {
      const params = {
        pageNum: 1,
        pageSize: 30
      };
      xymldSubmissionList(params).then(res => {
        const arr = [];
        const citys = [];
        res.data.forEach(el => {
          if (el.effectRange !== "湖北省") {
            const city = this.getYjtzdCity(el.effectRange);
            if (!citys.includes(city)) {
              citys.push(city);
              arr.push({
                dangerName: el.eventName,
                warningNoticeName: el.responseName,
                warningLvName: el.responseLvName,
                warningLvCode: el.responseLvCode,
                effectRange: city
              });
            }
          }
        });
        this.popupXyDOM = new SGMap.Popup({
          closeButton: false,
          closeOnClick: false,
          offset: {
            bottom: [0, 0]
          }
        });
        SGMap.plugin(["SGMap.DistrictTask"]).then(() => {
          const districtTask = new SGMap.DistrictTask();
          arr.forEach((el, index) => {
            this.drawXyImg(el, index, districtTask);
          });
        });
      });
    },
    draeHbLine() {
      SGMap.plugin(["SGMap.DistrictTask"]).then(() => {
        const districtTask = new SGMap.DistrictTask();
        // 行政区划名称查询行政区划;
        districtTask.searchDistrict({
          keyword: "湖北省",
          extension: true,
          subdistrict: "1"
        }).then((result) => {
          if (!result.data) return;
          result = result.data;
          if (!result.districts) {
            return;
          }
          var provinceFeatures = [];
          for (var i = 0; i < result.districts.length; i++) {
            provinceFeatures.push({
              type: "Feature",
              geometry: result.districts[i].shape
            });
          }
          this.map.addLayer({
            id: "power-line",
            type: "line",
            source: {
              type: "geojson",
              data: {
                type: "FeatureCollection",
                features: provinceFeatures
              }
            },
            paint: {
              "line-color": "#0064fc",
              "line-width": 2
            }
          });
        });
      });
    }
  }
};
